﻿Imports BusinessLayer
Imports CommonLayer
Imports System.ComponentModel
Imports Infragistics.Win.UltraWinToolbars
Imports Infragistics.Win.Misc
Imports Infragistics.Win.UltraWinTabControl
Imports System.Data.SqlClient
Imports Infragistics.Win.UltraWinEditors

Public Class frmBaseDictionaryDetail

#Region "Declaration"

    Protected bAllowClose As Boolean = False
    Protected eActionMode As EditMode

    Private m_strKeyObjectName As String = ""
    Protected m_sTableName As String
    Protected Const mscRequiredFieldSignal As String = "(*)"

    Protected oBLDictionary As BLDictionary

    Protected m_dsDictionary As DataSet
    Private m_strCurentCodeBeforeDeleteValue As String = ""
    Protected m_strDictionaryName As String = Me.Text
    Protected m_strCodeColumnName As String = ""
    Protected m_drDictionary As DataRow

    Protected m_firstFocusControl As Control = Nothing

    Private m_sPrimaryKeyColumnName As String

    Public IsLoaded As Boolean = False

    Protected ListOfEditControl As New List(Of Control)
    Public HasChange As Boolean = False

#End Region

#Region "Property"

    Public Overridable ReadOnly Property PermissionID() As PermissionEnum
        Get
            Return Nothing
        End Get
    End Property

    Public Overridable Property DictionaryObject() As BLDictionary
        Get
            Return oBLDictionary
        End Get
        Set(ByVal value As BLDictionary)
            oBLDictionary = value
        End Set
    End Property

    Public Overridable Property DictionaryDataSet() As DataSetDictionary
        Get
            Return dsDictionary
        End Get
        Set(ByVal value As DataSetDictionary)
            dsDictionary = value
        End Set
    End Property

    Public Overridable Property DictionaryData() As BindingSource
        Get
            Return bsList
        End Get
        Set(ByVal value As BindingSource)
            If value IsNot Nothing AndAlso value.Filter IsNot Nothing AndAlso value.Filter <> "" Then
                bsList.DataSource = value.DataSource
                bsList.DataMember = value.DataMember
                bsList.Sort = value.Sort
            Else
                bsList = value
            End If
        End Set
    End Property

    Public Overridable Property ActionMode() As EditMode
        Get
            Return eActionMode
        End Get
        Set(ByVal value As EditMode)
            eActionMode = value
            Select Case value
                Case EditMode.Add, EditMode.Edit
                    Me.SetEnableButtonOnToolbar(False)
                    Me.SetEnableControl(True)
                Case Else
                    Me.SetEnableButtonOnToolbar(True)
                    Me.SetEnableControl(False)
            End Select
        End Set
    End Property

    <Description("The Field name stored Code of the dictionary"), Category("HiSoft")> _
    Public Property CodeColumnName() As String
        Get
            Return m_strCodeColumnName
        End Get
        Set(ByVal value As String)
            m_strCodeColumnName = value
        End Set
    End Property

    Public Property DictionaryName() As String
        Get
            Return m_strDictionaryName
        End Get
        Set(ByVal value As String)
            m_strDictionaryName = value
        End Set
    End Property

    Public Overridable Property CurrentRow() As DataRow
        Get
            Return m_drDictionary
        End Get
        Set(ByVal value As DataRow)
            m_drDictionary = value
            If oBLDictionary IsNot Nothing Then
                oBLDictionary.CurrenceBusiness = value
            End If
        End Set
    End Property

    <Description("The primary key of the dictionary"), Category("HiSoft")> _
    Public Property PrimaryKeyColumnName() As String
        Get
            Return m_sPrimaryKeyColumnName
        End Get
        Set(ByVal Value As String)
            m_sPrimaryKeyColumnName = Value
        End Set
    End Property

#Region "Show/Hide Tool "

#End Region

#End Region

#Region "Constructor"

#End Region

#Region "Method"

#Region "Init Data"

    ''' <summary>
    ''' Hien thi du lieu cho cac combo
    ''' </summary>
    Protected Overridable Sub InitDataToCombo()
    End Sub


    Protected Overridable Function InitAddNewRow() As DataRow
        Return Nothing
    End Function

#End Region


#Region "Validate"

    Protected Overridable Function MustSaveData() As Boolean
        Dim blnResult As Boolean = False
        If (Not IsNothing(bsList)) AndAlso Not oBLDictionary Is Nothing Then
            bsList.EndEdit()

            If Not IsNothing(oBLDictionary.BusinessObject.Tables(oBLDictionary.TableName).GetChanges) Then
                blnResult = oBLDictionary.BusinessObject.GetChanges.Tables(oBLDictionary.TableName).Rows.Count > 0
            Else
                blnResult = False
            End If
        End If
        Return blnResult
    End Function

    Protected Overridable Function ValidateData() As Boolean
        Dim bResult = ValidRequiredInfo(Me)

        Return bResult
    End Function

    Protected Overridable Function ValidRequiredInfo(ByRef oContainer As Control) As Boolean
        Dim dtControl As New DataTable
        dtControl.Columns.Add("Control", GetType(Control))
        dtControl.Columns.Add("TabIndex", GetType(Integer))

        For Each oChildControl As Control In oContainer.Controls
            dtControl.Rows.Add(oChildControl, oChildControl.TabIndex)
        Next
        dtControl.DefaultView.Sort = "TabIndex"
        '--------------------------------------------------------------------------------------------------------------
        Dim oControl As Control
        Dim oControlFocus As Control = Nothing

        For Each drvControl As DataRowView In dtControl.DefaultView
            oControl = drvControl(0)

            Select Case oControl.GetType.Name
                Case GetType(UltraLabel).Name

                    If oControl.Text.Trim.EndsWith(mscRequiredFieldSignal) Then
                        oControlFocus = Me.GetNextControl(oControl, True)

                        If Not IsNothing(oControlFocus) Then
                            If String.IsNullOrEmpty(oControlFocus.Text) OrElse oControlFocus.Text.Trim = "" Then
                                If oControlFocus.Parent.GetType Is GetType(UltraTabPageControl) Then
                                    Dim oTabPage As UltraTabPageControl = oControlFocus.Parent
                                    oTabPage.TabControl.SelectedTab = oTabPage.Tab
                                Else
                                    If _
                                        oControlFocus.Parent.Parent IsNot Nothing AndAlso _
                                        oControlFocus.Parent.Parent.GetType Is GetType(UltraTabPageControl) Then
                                        Dim oTabPage As UltraTabPageControl = oControlFocus.Parent.Parent
                                        oTabPage.TabControl.SelectedTab = oTabPage.Tab
                                    End If
                                End If
                                oControlFocus.Focus()
                                CommonFunction.ShowExclamation(String.Format(My.Resources.Dictionary_Data_NotAllowBlank, _
                                                                             CommonFunction.RefineTitleText( _
                                                                                 oControl.Text)))
                                Return False
                            Else
                                If oControlFocus.DataBindings.Count > 0 Then
                                    If _
                                        oControlFocus.DataBindings.Item(0).BindingMemberInfo.BindingField = _
                                        m_strCodeColumnName Then
                                        If Not VerifyCode() Then

                                            CommonFunction.ShowExclamation( _
                                                String.Format(My.Resources.Dictionary_Data_Update_CodeExist, _
                                                              CommonFunction.RefineTitleText(oControl.Text), _
                                                              oControlFocus.Text))
                                            oControlFocus.Focus()
                                            Return False
                                        End If
                                    End If
                                End If
                            End If
                        End If
                    End If
                Case Else
                    If oControl.Controls.Count > 0 Then
                        If Not ValidRequiredInfo(oControl) Then Return False
                    End If
            End Select
        Next
        Return True
    End Function

    Protected Overridable Function GetNextControlValidate(ByVal oControl As Control) As Control
        Dim oResult As Control = Nothing
        If oControl IsNot Nothing Then
            oResult = Me.GetNextControl(oControl, True)
        End If

        Return oResult
    End Function

    Public Overridable Function VerifyCode() As Boolean
        Dim blnResult As Boolean = True
        Dim drDictionary As DataRow
        drDictionary = CommonFunction.GetCurrentRow(bsList)

        blnResult = _
            Not _
            oBLDictionary.CheckExistAlias(m_strCodeColumnName, drDictionary(m_strCodeColumnName), _
                                          drDictionary(m_sPrimaryKeyColumnName))

        Return blnResult
    End Function

#End Region


#Region "CRUD"

    Protected Friend Overridable Sub NewDictionary()
        If Not CommonFunction.CheckPermissionByID(CommonFunction.MySession.CurrentUser, PermissionID, ActionEnum.AddNew) Then
            Return
        End If
        Dim drNew As DataRow = InitAddNewRow()
        If drNew IsNot Nothing Then
            If m_firstFocusControl IsNot Nothing Then
                m_firstFocusControl.Focus()
            End If

            bsList.Position = bsList.Find(m_sPrimaryKeyColumnName, drNew(m_sPrimaryKeyColumnName))
            If bsList.Position >= 0 Then
                CurrentRow = drNew
                ActionMode = EditMode.Add
            End If
        End If
    End Sub

    Protected Friend Overridable Sub EditDictionary()
        If Not CommonFunction.CheckPermissionByID(CommonFunction.MySession.CurrentUser, PermissionID, ActionEnum.Edit) Then
            Return
        End If

        ActionMode = EditMode.Edit
    End Sub

    Friend Overridable Sub RefineControl()
    End Sub


    Public Overridable Function EditDictionary(ByVal strID As String) As Boolean

        If Not CommonFunction.CheckPermissionByID(CommonFunction.MySession.CurrentUser, Me.PermissionID, ActionEnum.Edit) Then
            Return False
        End If
        ActionMode = EditMode.Edit
        Return True
    End Function

    ''' <summary>
    ''' Xóa dong Dictionary
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Protected Friend Overridable Function DeleteDictionary() As Boolean
        Try
            Dim strDeletedErrMess As String = String.Empty
            Dim sDictionaryCanNotDelete As String = String.Empty
            Dim blnResult As Boolean = False

            If Not CommonFunction.CheckPermissionByID(CommonFunction.MySession.CurrentUser, PermissionID, ActionEnum.Delete) Then
                Return False
            End If

            If CommonFunction.ShowQuestionMessage(My.Resources.Delete_Single_Confirm_Alert, MessageBoxButtons.YesNo) = _
                DialogResult.No Then
                Return blnResult
            Else

                Dim strPrimaryKey As String = oBLDictionary.PrimaryKey
                Dim sValue As String = CurrentRow(m_strCodeColumnName)
                Dim guiID As Guid = CurrentRow(strPrimaryKey)

                Try
                    If CurrentRow.Table.Columns.Contains("IsSystem") AndAlso CurrentRow.Item("IsSystem") Then
                        CommonFunction.ShowExclamation("Bạn không thể xóa vì << " & sValue & " >> thuộc về hệ thống.")
                        Return False
                    Else
                        If Not oBLDictionary.DeleteRow(guiID) Then
                            CommonFunction.ShowExclamation("Có lỗi xảy ra khi xóa << " & sValue & " >>.")
                            Return False
                        Else
                            blnResult = True
                            HasChange = True
                        End If
                    End If

                Catch exSQL As SqlException
                    If exSQL.Number = CommonFunction.mscSQLExceptionContrainsNumber Then
                        CommonFunction.ShowExclamation("Bạn không thể xóa vì << " & sValue & " >> đã có phát sinh.")
                        Return False
                    End If
                End Try

                If blnResult Then
                    CurrentRow.Delete()
                    If bsList.Position >= 0 Then
                        CurrentRow = CommonFunction.GetCurrentRow(bsList)
                        oBLDictionary.CurrenceBusiness = CurrentRow
                    End If
                End If

                oBLDictionary.AcceptChange()

                If bsList.Count <= 0 Then
                    Close()
                End If
            End If
            Return blnResult
        Catch ex As Exception
            CommonFunction.ShowExceptionMessage(ex)
        End Try
    End Function

#End Region

#Region "Others"

    Protected Overridable Sub BindingData(ByVal oContainer As Control)
        Dim myControl As Control
        Dim strTag As String = String.Empty
        'Nothing
        If Not IsNothing(bsList) AndAlso Not IsNothing(oBLDictionary) Then
            For Each myControl In oContainer.Controls
                strTag = CStr(myControl.Tag)
                If Not IsNothing(strTag) AndAlso strTag <> "" Then
                    If (myControl.GetType Is GetType(UltraTextEditor)) OrElse (myControl.GetType Is GetType(UltraLabel)) _
                        Then
                        If _
                            oBLDictionary.BusinessObject.Tables(oBLDictionary.TableName).Columns(strTag).DataType Is _
                            GetType(DateTime) Then
                            myControl.DataBindings.Add("Text", bsList, strTag, True, _
                                                       DataSourceUpdateMode.OnPropertyChanged, "", _
                                                       CommonFunction.DateFormatString)
                        ElseIf _
                            oBLDictionary.BusinessObject.Tables(oBLDictionary.TableName).Columns(strTag).DataType Is _
                            GetType(Decimal) Then
                            myControl.DataBindings.Add("Text", bsList, strTag, True, _
                                                       DataSourceUpdateMode.OnPropertyChanged)
                        Else
                            myControl.DataBindings.Add("Text", bsList, strTag)
                        End If

                    Else
                        If Not IsNothing(myControl.GetType.GetProperty("Checked")) Then
                            myControl.DataBindings.Add("Checked", bsList, strTag)
                        Else
                            myControl.DataBindings.Add("Value", bsList, strTag)
                        End If
                    End If
                Else
                    If myControl.Controls.Count > 0 Then
                        BindingData(myControl)
                    End If
                End If
            Next
        End If
    End Sub

    ''' <summary>
    ''' set enable toolbutton 
    ''' </summary>
    ''' <param name="bEnable"></param>
    ''' <remarks></remarks>
    Protected Overridable Sub SetEnableButtonOnToolbar(ByVal bEnable As Boolean)
        Try
            With ToolbarsManager.Tools
                .Item("mnuAdd").SharedProps.Enabled = bEnable
                .Item("mnuEdit").SharedProps.Enabled = bEnable
                .Item("mnuDelete").SharedProps.Enabled = bEnable
                .Item("mnuSave").SharedProps.Enabled = Not bEnable
                .Item("mnuCancel").SharedProps.Enabled = Not bEnable
                .Item("mnuClose").SharedProps.Enabled = True
            End With
        Catch ex As Exception
            CommonFunction.ShowExceptionMessage(ex)
        End Try
    End Sub

    ''' <summary>
    ''' set enable toolbutton 
    ''' </summary>
    ''' <param name="bEnable"></param>
    ''' <remarks></remarks>
    Protected Overridable Sub SetEnableControl(ByVal bEnable As Boolean)
    End Sub

    Protected Function PreSaveData() As Boolean
        Dim bResult As Boolean = False
        bsList.EndEdit()
        If Me.Validate AndAlso ValidateData() Then
            If MustSaveData() Then
                bResult = SaveDictionary()
            Else
                bResult = True
            End If
        End If

        If bResult Then
            Me.ActionMode = EditMode.View
        End If

        Return bResult
    End Function

    Protected Overridable Function SaveDictionary() As Boolean
        Dim bResult As Boolean = False
        Dim strDictionaryCode As String = ""

        Select Case eActionMode
            Case EditMode.Add
                bResult = InsertNewDictionary()
            Case EditMode.Edit
                bResult = UpdateDictionary()
        End Select

        If bResult Then
            AcceptChange()
            HasChange = True
        End If


        Return bResult
    End Function

    Protected Overridable Function InsertNewDictionary() As Boolean
        Return oBLDictionary.InsertRow(CommonFunction.GetCurrentRow(bsList))
    End Function


    Protected Overridable Function UpdateDictionary() As Boolean
        Return oBLDictionary.UpdateRow(CommonFunction.GetCurrentRow(bsList))
    End Function

    Protected Overridable Sub AcceptChange()
        oBLDictionary.AcceptChange()
    End Sub


    Protected Overridable Sub CancelForm()
        If Not IsNothing(bsList) AndAlso Not oBLDictionary Is Nothing Then
            bsList.CancelEdit()
            'bsList.EndEdit()

            With oBLDictionary
                .RejectChange()
                '.BusinessData.Tables(.TableName).AcceptChanges()
            End With
        End If

        Me.ActionMode = EditMode.View
        If bsList.Count <= 0 Then
            Me.Close()
        Else
            Me.CurrentRow = CommonFunction.GetCurrentRow(bsList)
        End If
    End Sub

    Protected Overridable Function GetDictionaryCodeName() As String
        Dim sDictinary As String = Nothing
        Select Case Me.m_strCodeColumnName
            Case "AccountNumber"
                If Not IsNothing(Me.m_strCodeColumnName) Then
                    sDictinary = Me.m_strCodeColumnName
                End If
            Case Else
                If Not IsNothing(Me.m_sPrimaryKeyColumnName) Then
                    sDictinary = Me.m_sPrimaryKeyColumnName
                Else
                    sDictinary = Nothing
                End If
        End Select
        Return sDictinary
    End Function

    Protected Overridable Sub ClosingForm(ByVal sender As Object, ByVal e As FormClosingEventArgs)
        If Not bAllowClose AndAlso MustSaveData() Then
            Select Case _
                MessageBox.Show(My.Resources.Dictionary_DataChangeConfirm, Application.ProductName, _
                                MessageBoxButtons.YesNoCancel, MessageBoxIcon.Exclamation)
                Case DialogResult.Yes
                    bAllowClose = PreSaveData()
                    e.Cancel = Not bAllowClose
                    If bAllowClose Then
                        Me.DialogResult = DialogResult.OK
                    End If
                Case DialogResult.No
                    CancelForm()
                Case DialogResult.Cancel
                    bAllowClose = False
                    e.Cancel = True
            End Select
            If bAllowClose Then
                bsList = Nothing
            End If
        End If
    End Sub


#End Region

#Region "Private Method"

    Protected Overridable Sub BindingSourcePositionChanged()
    End Sub

    Protected Overridable Sub ToolClick(ByVal tool As ToolBase)
        If tool.Key IsNot Nothing Then
            Select Case tool.Key
                Case "mnuAdd" ' ButtonTool
                    ' Place code here
                    Me.NewDictionary()
                Case "mnuEdit" ' ButtonTool
                    ' Place code here
                    Me.EditDictionary()

                Case "mnuDelete" ' ButtonTool
                    ' Place code here
                    Me.DeleteDictionary()

                Case "mnuSave" ' ButtonTool
                    Me.PreSaveData()
                Case "mnuCancel" ' ButtonTool
                    Me.CancelForm()
                Case "mnuClose" ' ButtonTool
                    Me.Close()
            End Select

        End If
    End Sub

#End Region

#End Region

#Region "Events"

    Private Sub frmBaseDictionaryDetail_FormClosing(ByVal sender As Object, ByVal e As FormClosingEventArgs) _
        Handles Me.FormClosing
        Try
            If Me.ActionMode <> EditMode.View Then
                Me.ClosingForm(sender, e)
            End If

        Catch ex As Exception
            CommonFunction.ShowExceptionMessage(ex)
        End Try
    End Sub

    Private Sub frmBaseDictionaryDetail_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
        Try
            Me.InitDataToCombo()
            Me.BindingData(Me)

            IsLoaded = True
        Catch ex As Exception
            CommonFunction.ShowExceptionMessage(ex)
        End Try
    End Sub

    Private Sub ToolbarsManager_ToolClick(ByVal sender As Object, ByVal e As ToolClickEventArgs) _
        Handles ToolbarsManager.ToolClick
        Try
            Me.Cursor = Cursors.WaitCursor
            ToolClick(e.Tool)

        Catch ex As Exception
            CommonFunction.ShowExclamation(ex.ToString)
        Finally
            Me.Cursor = Cursors.Default
        End Try
    End Sub

    Private Sub bsList_PositionChanged(ByVal sender As Object, ByVal e As EventArgs) Handles bsList.PositionChanged
        Try
            Me.BindingSourcePositionChanged()
        Catch ex As Exception
            CommonFunction.ShowExceptionMessage(ex)
        End Try
    End Sub

#End Region
End Class